package com.zys.sac.uc.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zys.sac.uc.entity.SacOrganization;
import com.zys.sac.uc.entity.SacRole;
import com.zys.sac.uc.entity.SacUser;
import com.zys.sac.uc.vo.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author sz
 * @since 2022-06-01
 */
@Service("sacUserService")
public class SysUserServiceImpl implements UserDetailsService {

    @Autowired
    private ISacUserService sacUserService;

    @Autowired
    private ISacRoleService sacRoleService;

    @Autowired
    private ISacOrganizationService sacOrganizationService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<SacUser> userQuery = new LambdaQueryWrapper<>();
        userQuery.eq(SacUser::getUsername, username);
        SacUser user = sacUserService.getOne(userQuery);
        if (null == user) {
            throw new UsernameNotFoundException("未找到登录用户信息");
        }
        UserInfoVO currentUser = new UserInfoVO();
        BeanUtil.copyProperties(user, currentUser, false);
        List<SacRole> roles = sacRoleService.findByUserCode(currentUser.getCode());
        List<SacOrganization> organizations = sacOrganizationService.findByUserCode(currentUser.getCode());
        currentUser.setRoleList(roles);
        currentUser.setOrganizationList(organizations);
        return currentUser;
    }
}
